<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>共享出行 - 行程历史</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        
        .header {
            background-color: #007bff;
            color: white;
            padding: 0 20px;
            height: 50px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 {
            margin: 0;
            font-size: 1.2rem;
        }
        .nav-buttons {
            display: flex;
            gap: 10px;
        }
        .nav-button {
            background: transparent;
            border: 1px solid rgba(255, 255, 255, 0.5);
            border-radius: 4px;
            color: white;
            padding: 6px 12px;
            cursor: pointer;
            transition: background-color 0.2s;
            font-size: 14px;
        }
        .nav-button:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }
        .username {
            margin-right: 15px;
            font-size: 14px;
        }
        
        .container {
            max-width: 900px;
            margin: 20px auto;
            padding: 20px;
        }
        
        .filter-bar {
            background: white;
            padding: 15px 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            margin-bottom: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: center;
        }
        
        .filter-group {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .filter-label {
            font-weight: bold;
            color: #555;
        }
        
        .filter-select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .trip-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        
        .trip-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
            overflow: hidden;
        }
        
        .trip-header {
            padding: 15px 20px;
            background: #f5f5f5;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .trip-id {
            font-weight: bold;
            color: #007bff;
        }
        
        .trip-status {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .status-completed {
            background: #e8f5e9;
            color: #2e7d32;
        }
        
        .status-cancelled {
            background: #ffebee;
            color: #c62828;
        }
        
        .trip-body {
            padding: 15px 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .trip-info {
            flex: 1;
            min-width: 250px;
        }
        
        .info-item {
            margin-bottom: 10px;
            display: flex;
            flex-wrap: wrap;
        }
        
        .info-label {
            font-weight: bold;
            width: 100px;
            color: #666;
        }
        
        .info-value {
            flex: 1;
        }
        
        .trip-map {
            width: 100%;
            height: 200px;
            margin: 10px 0;
            border-radius: 4px;
            overflow: hidden;
            display: none; /* 默认隐藏地图 */
        }
        
        .trip-actions {
            padding: 10px 20px;
            background: #f9f9f9;
            border-top: 1px solid #eee;
            text-align: right;
        }
        
        .btn {
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
            margin-left: 10px;
            transition: background-color 0.2s;
        }
        
        .btn-primary {
            background: #007bff;
            color: white;
        }
        
        .btn-primary:hover {
            background: #0056b3;
        }
        
        .btn-secondary {
            background: #f2f2f2;
            color: #333;
        }
        
        .btn-secondary:hover {
            background: #ddd;
        }
        
        .empty-state {
            text-align: center;
            padding: 50px 0;
            color: #666;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
            gap: 5px;
        }
        
        .page-btn {
            padding: 8px 12px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .page-btn.active {
            background: #007bff;
            color: white;
            border-color: #007bff;
        }
        
        .page-btn:hover:not(.active) {
            background: #f5f5f5;
        }
        
        .loading {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255,255,255,0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            visibility: hidden;
            opacity: 0;
            transition: opacity 0.3s, visibility 0.3s;
        }
        
        .loading.show {
            visibility: visible;
            opacity: 1;
        }
        
        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #007bff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .filter-bar {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .trip-body {
                flex-direction: column;
            }
            
            .info-label {
                width: 120px;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>共享出行系统</h1>
        <div class="nav-buttons">
            <span class="username" id="usernameDisplay"></span>
            <button class="nav-button" onclick="window.location.href='vehicle-list.html'">车辆租赁</button>
            <button class="nav-button" onclick="window.location.href='trip.html'">当前行程</button>
            <button class="nav-button" onclick="window.location.href='payment.html'">支付中心</button>
            <button class="nav-button" onclick="window.location.href='edit-profile.html'">个人资料</button>
            <button class="nav-button" onclick="logout()">退出登录</button>
        </div>
    </div>

    <div class="container">
        <div class="filter-bar">
            <div class="filter-group">
                <span class="filter-label">状态:</span>
                <select id="statusFilter" class="filter-select" onchange="applyFilters()">
                    <option value="all">全部</option>
                    <option value="2">已完成</option>
                    <option value="3">已取消</option>
                </select>
            </div>
            <div class="filter-group">
                <span class="filter-label">支付状态:</span>
                <select id="paymentFilter" class="filter-select" onchange="applyFilters()">
                    <option value="all">全部</option>
                    <option value="true">已支付</option>
                    <option value="false">未支付</option>
                </select>
            </div>
            <div class="filter-group">
                <span class="filter-label">排序:</span>
                <select id="sortFilter" class="filter-select" onchange="applyFilters()">
                    <option value="newest">最新优先</option>
                    <option value="oldest">最早优先</option>
                </select>
            </div>
        </div>

        <div id="tripList" class="trip-list">
            <!-- 行程列表将通过JavaScript动态生成 -->
        </div>

        <div id="pagination" class="pagination">
            <!-- 分页将通过JavaScript动态生成 -->
        </div>
    </div>

    <div id="loading" class="loading">
        <div class="spinner"></div>
    </div>

    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
    <script>
        // 全局变量
        let allTrips = [];
        let filteredTrips = [];
        let currentPage = 1;
        const tripsPerPage = 5;
        const tripMaps = {};

        document.addEventListener('DOMContentLoaded', async function() {
            await checkLogin();
            fetchTrips();
        });

        // 检查登录状态
        async function checkLogin() {
            showLoading();
            try {
                const response = await fetch('api/check-login', {
                    credentials: 'include'
                });
                const result = await response.json();
                hideLoading();
                
                if (!result.success) {
                    window.location.href = 'login.html';
                    return false;
                }
                
                // 显示用户名
                document.getElementById('usernameDisplay').textContent = result.data.username;
                
                return true;
            } catch (error) {
                hideLoading();
                console.error('检查登录状态失败:', error);
                window.location.href = 'login.html';
                return false;
            }
        }

        // 退出登录
        async function logout() {
            try {
                showLoading();
                const response = await fetch('api/logout', {
                    method: 'POST',
                    credentials: 'include'
                });
                const result = await response.json();
                
                hideLoading();
                if (result.success) {
                    window.location.href = 'login.html';
                }
            } catch (error) {
                hideLoading();
                console.error('退出登录失败:', error);
            }
        }

        // 获取用户行程历史
        async function fetchTrips() {
            showLoading();
            try {
                const response = await fetch('api/trips/history', {
                    credentials: 'include'
                });
                const result = await response.json();
                hideLoading();
                
                if (result.success) {
                    allTrips = result.data;
                    applyFilters();
                } else {
                    displayEmptyState('获取行程历史失败: ' + result.message);
                }
            } catch (error) {
                hideLoading();
                console.error('获取行程历史失败:', error);
                displayEmptyState('获取行程历史失败，请稍后重试');
            }
        }

        // 应用筛选条件
        function applyFilters() {
            const statusFilter = document.getElementById('statusFilter').value;
            const paymentFilter = document.getElementById('paymentFilter').value;
            const sortFilter = document.getElementById('sortFilter').value;
            
            // 筛选
            filteredTrips = allTrips.filter(trip => {
                // 状态筛选
                if (statusFilter !== 'all' && trip.status != statusFilter) {
                    return false;
                }
                
                // 支付状态筛选
                if (paymentFilter !== 'all') {
                    const isPaid = String(trip.paid) === 'true';
                    if (String(paymentFilter) === 'true' && !isPaid) {
                        return false;
                    }
                    if (String(paymentFilter) === 'false' && isPaid) {
                        return false;
                    }
                }
                
                return true;
            });
            
            // 排序
            filteredTrips.sort((a, b) => {
                const timeA = new Date(a.startTime).getTime();
                const timeB = new Date(b.startTime).getTime();
                return sortFilter === 'newest' ? timeB - timeA : timeA - timeB;
            });
            
            // 重置到第一页
            currentPage = 1;
            
            // 渲染
            renderTrips();
        }

        // 渲染行程列表
        function renderTrips() {
            const tripListElement = document.getElementById('tripList');
            
            // 如果没有行程数据
            if (filteredTrips.length === 0) {
                displayEmptyState('没有符合条件的行程记录');
                document.getElementById('pagination').innerHTML = '';
                return;
            }
            
            // 计算分页
            const totalPages = Math.ceil(filteredTrips.length / tripsPerPage);
            const startIdx = (currentPage - 1) * tripsPerPage;
            const endIdx = Math.min(startIdx + tripsPerPage, filteredTrips.length);
            const currentTrips = filteredTrips.slice(startIdx, endIdx);
            
            // 生成行程列表HTML
            let html = '';
            
            currentTrips.forEach(trip => {
                const vehicle = trip.vehicle || {
                    type: '未知',
                    brand: '未知',
                    model: '未知',
                    plateNumber: '未知'
                };
                
                const startTime = new Date(trip.startTime).toLocaleString();
                const endTime = trip.endTime ? new Date(trip.endTime).toLocaleString() : '未结束';
                
                // 根据状态显示不同的标签
                let statusClass = '';
                let statusText = '';
                switch(trip.status) {
                    case 0:
                        statusClass = 'status-in-progress';
                        statusText = '进行中';
                        break;
                    case 1:
                        statusClass = 'status-completed';
                        statusText = '已完成';
                        break;
                    case 2:
                        statusClass = 'status-completed';
                        statusText = '已完成';
                        break;
                    case 3:
                        statusClass = 'status-cancelled';
                        statusText = '已取消';
                        break;
                    default:
                        statusClass = '';
                        statusText = '未知状态';
                }
                
                html += `
                    <div class="trip-card">
                        <div class="trip-header">
                            <div class="trip-id">行程编号: ${trip.id}</div>
                            <div class="trip-status ${statusClass}">${statusText}</div>
                        </div>
                        <div class="trip-body">
                            <div class="trip-info">
                                <div class="info-item">
                                    <div class="info-label">车辆:</div>
                                    <div class="info-value">${getTypeText(vehicle.type)} ${vehicle.brand} ${vehicle.model}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">车牌号:</div>
                                    <div class="info-value">${vehicle.plateNumber}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">开始时间:</div>
                                    <div class="info-value">${startTime}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">结束时间:</div>
                                    <div class="info-value">${endTime}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">行驶距离:</div>
                                    <div class="info-value">${trip.distance ? trip.distance + ' 公里' : '未记录'}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">费用:</div>
                                    <div class="info-value">¥${trip.cost ? trip.cost.toFixed(2) : '0.00'}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">支付状态:</div>
                                    <div class="info-value">${trip.paid ? '已支付' : '未支付'}</div>
                                </div>
                            </div>
                            <div id="map-${trip.id}" class="trip-map"></div>
                        </div>
                        <div class="trip-actions">
                            <button class="btn btn-secondary" onclick="toggleMap(${trip.id})">查看地图</button>
                            ${!trip.paid ? `<button class="btn btn-primary" onclick="window.location.href='payment.html'">去支付</button>` : ''}
                        </div>
                    </div>
                `;
            });
            
            tripListElement.innerHTML = html;
            renderPagination(totalPages);
        }

        // 显示地图
        function toggleMap(tripId) {
            const mapElement = document.getElementById(`map-${tripId}`);
            
            if (mapElement.style.display === 'block') {
                mapElement.style.display = 'none';
                return;
            }
            
            mapElement.style.display = 'block';
            
            // 如果地图已经初始化过，则不再重复初始化
            if (tripMaps[tripId]) {
                return;
            }
            
            const trip = filteredTrips.find(t => t.id === tripId);
            if (!trip || !trip.vehicle) return;
            
            const startLat = trip.vehicle.latitude || 30.274084;
            const startLng = trip.vehicle.longitude || 120.155070;
            
            const map = L.map(`map-${tripId}`).setView([startLat, startLng], 15);
            
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; OpenStreetMap contributors'
            }).addTo(map);
            
            L.marker([startLat, startLng]).addTo(map)
                .bindPopup(`${trip.vehicle.brand} ${trip.vehicle.model}`)
                .openPopup();
                
            // 存储地图实例以便后续使用
            tripMaps[tripId] = map;
            
            // 触发地图重绘以正确显示
            setTimeout(() => {
                map.invalidateSize();
            }, 100);
        }

        // 渲染分页
        function renderPagination(totalPages) {
            if (totalPages <= 1) {
                document.getElementById('pagination').innerHTML = '';
                return;
            }
            
            let html = '';
            
            // 添加上一页按钮
            html += `<button class="page-btn" ${currentPage === 1 ? 'disabled' : ''} onclick="changePage(${currentPage - 1})">上一页</button>`;
            
            // 添加页码按钮
            for (let i = 1; i <= totalPages; i++) {
                if (
                    i === 1 || // 第一页
                    i === totalPages || // 最后一页
                    (i >= currentPage - 1 && i <= currentPage + 1) // 当前页附近的页码
                ) {
                    html += `<button class="page-btn ${currentPage === i ? 'active' : ''}" onclick="changePage(${i})">${i}</button>`;
                } else if (i === currentPage - 2 || i === currentPage + 2) {
                    html += `<span class="page-btn">...</span>`;
                }
            }
            
            // 添加下一页按钮
            html += `<button class="page-btn" ${currentPage === totalPages ? 'disabled' : ''} onclick="changePage(${currentPage + 1})">下一页</button>`;
            
            document.getElementById('pagination').innerHTML = html;
        }

        // 切换页码
        function changePage(page) {
            currentPage = page;
            renderTrips();
            // 滚动到页面顶部
            window.scrollTo(0, 0);
        }

        // 显示空状态
        function displayEmptyState(message) {
            const tripListElement = document.getElementById('tripList');
            tripListElement.innerHTML = `
                <div class="empty-state">
                    <h3>${message}</h3>
                    <p>您可以尝试调整筛选条件或返回首页</p>
                    <button class="btn btn-primary" onclick="window.location.href='vehicle-list.html'">返回首页</button>
                </div>
            `;
        }

        // 获取车辆类型文本
        function getTypeText(type) {
            switch (type) {
                case 'car': return '汽车';
                case 'e-bike': return '电动车';
                case 'bicycle': return '自行车';
                default: return type;
            }
        }

        // 显示加载动画
        function showLoading() {
            document.getElementById('loading').classList.add('show');
        }

        // 隐藏加载动画
        function hideLoading() {
            document.getElementById('loading').classList.remove('show');
        }
    </script>
</body>
</html> 